package com.farm.system.controller;

import com.farm.constant.MessageConstant;
import com.farm.entity.PageResult;
import com.farm.entity.Result;
import com.farm.entity.StatusCode;
import com.farm.system.pojo.Role;
import com.farm.system.service.RoleService;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 角色控制层
 *
 * @author Chengfei
 * @date 2020/10/11
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    /**
     * 查询所有角色 用于回显所有角色供用户选择
     *
     * @return 角色集合
     */
    @GetMapping("/findAll")
    public Result findAll() {
        List<Role> roleList = roleService.findAll();
        return new Result(true, StatusCode.OK, MessageConstant.SELECT_ALL_ROLE_SUCCESS, roleList);
    }


    /**
     * 条件分页查询
     *
     * @param page      页码
     * @param size      大小
     * @param searchMap 查询条件
     * @return 角色集合
     */
    @GetMapping("/findPageByCondition")
    public Result findPageByCondition(@RequestParam(name = "page", required = false, defaultValue = "1") Integer page,
                                      @RequestParam(name = "size", required = false, defaultValue = "10") Integer size,
                                      @RequestParam Map<String, Object> searchMap) {

        Page<Role> pageList = roleService.findPageByCondition(page, size, searchMap);
        PageResult pageResult = new PageResult(pageList.getTotal(), pageList.getResult());
        return new Result(true, StatusCode.OK, MessageConstant.SELECT_ROLE_SUCCESS, pageResult);
    }


    /**
     * 添加角色
     *
     * @param role    角色
     * @param menuIds 菜单id数组
     * @return 无
     */
    @PostMapping("/add")
    public Result add(@RequestBody Role role, @RequestParam Integer[] menuIds) {
        roleService.add(role, menuIds);
        return new Result(true, StatusCode.OK, MessageConstant.ADD_ROLE_SUCCESS);
    }

    /**
     * 更新角色
     *
     * @param role    角色
     * @param menuIds 菜单id数组
     * @return 无
     */
    @PutMapping("/update")
    public Result update(@RequestBody Role role, @RequestParam Integer[] menuIds) {
        roleService.update(role, menuIds);
        return new Result(true, StatusCode.OK, MessageConstant.UPDATE_ROLE_SUCCESS);
    }

    /**
     * 删除角色
     *
     * @param roleId 角色id
     * @return 无
     */
    @DeleteMapping("/delete/{roleId}")
    public Result delete(@PathVariable("roleId") Integer roleId) {
        roleService.delete(roleId);
        return new Result(true, StatusCode.OK, MessageConstant.DELETE_ROLE_SUCCESS);
    }

}
